package com.annotation.database;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析注解
 * 
 * @author Administrator
 *
 */
public class TableCreator {

	public static void main(String[] args) throws Exception {
		args = new String[] { "com.annotation.database.Member" };

		for (String className : args) {
			Class<?> cl = Class.forName(className);
			DBTable dbTable = cl.getAnnotation(DBTable.class);
			if (dbTable == null) {
				System.out.println("No DBTable annotations in class "
						+ className);
				continue;
			}
			String tableName = dbTable.name();
			// 假如tableName为空，就用类的名字
			if (tableName.length() < 1) {
				tableName = cl.getName().toUpperCase();
			}

			List<String> columnDefs = new ArrayList<String>();
			for (Field field : cl.getDeclaredFields()) {
				String columnName = null;
				Annotation[] anns = field.getDeclaredAnnotations();
				if (anns.length < 1) {
					continue;// 不是数据库列
				}
				if (anns[0] instanceof SQLInteger) {
					SQLInteger sInt = (SQLInteger) anns[0];
					if (sInt.name().length() < 1) {
						columnName = field.getName().toUpperCase();// 假如没有指定数据库字段名就使用域名称
					} else {
						columnName = sInt.name();
					}
					columnDefs.add(columnName + " int"
							+ getConstraints(sInt.constraints()));
				}

				if (anns[0] instanceof SQLString) {
					SQLString sString = (SQLString) anns[0];
					if (sString.name().length() < 1) {
						columnName = field.getName().toUpperCase();// 假如没有指定数据库字段名就使用域名称
					} else {
						columnName = sString.name();
					}
					columnDefs.add(columnName + " varchar(" + sString.value()
							+ ")" + getConstraints(sString.constraints()));
				}

			}
			StringBuilder createCommand = new StringBuilder("create table "
					+ tableName + "(");
			for (String columnDef : columnDefs) {
				createCommand.append("\n    " + columnDef + ",");
			}
			String tableCreate = createCommand.substring(0,
					createCommand.length() - 1)
					+ ")";
			System.out.println("table creation sql for " + className
					+ " is: \n" + tableCreate);
		}
	}

	// 生成字段约束信息
	public static String getConstraints(Constraints con) {
		String constraints = "";
		if (!con.allowNull()) {
			constraints += " not null";
		}
		if (con.primaryKey()) {
			constraints += " primary key";
		}
		if (con.unique()) {
			constraints += " unique";
		}
		return constraints;
	}

}
